package org.example;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


public class GoldCalc {
    private static final List<String> SPECIAL_DATE_STR = Arrays.asList("修改订单", "提醒卖家发货", "申请开票");
    private static final String PACKAGE_PATH = "C:\\Users\\boge\\Desktop\\金子计算\\";
    private static final List<String> SPECIAL_SKU_STR = Arrays.asList("（3mm亮面金珠）");

    public static void main(String[] args) throws Exception {
//        System.out.println("发财了");
        int strLength = 9;
        List<TaobaoOrder> taobaoOrderList = new ArrayList<>();
        // 获取文件的输入流
        String content = loadStr("data.txt");
        List<JSONObject> jsonObjects = parseMultipleJsonsFromFile(content);
        for (JSONObject jsonObject : jsonObjects) {
            JSONArray mainOrders = jsonObject.getJSONArray("mainOrders");
            for (int i = 0; i < mainOrders.size(); i++) {
                JSONObject mainOrderChild = mainOrders.getJSONObject(i);
                TaobaoOrder taobaoOrder = new TaobaoOrder();
                JSONObject seller = mainOrderChild.getJSONObject("seller");
                JSONObject payInfo = mainOrderChild.getJSONObject("payInfo");
                JSONArray subOrders = mainOrderChild.getJSONArray("subOrders");
                JSONArray operations = mainOrderChild.getJSONArray("operations");
//                    if (!(seller.getStr("shopName")).contains("吾皇老金珠宝旗舰店")) {
//                        continue;
//                    }
//                    System.out.println(mainOrderChild);
                double totalG = 0d;
                double realTotal = 0d;
                for (int j = 0; j < subOrders.size(); j++) {
                    JSONObject subOrder = subOrders.getJSONObject(j);
                    Double quantity = subOrder.getDouble("quantity");
                    JSONObject itemInfo = subOrder.getJSONObject("itemInfo");
                    JSONObject priceInfo = subOrder.getJSONObject("priceInfo");
                    JSONArray skuText = itemInfo.getJSONArray("skuText");
                    if (Objects.isNull(skuText)) {
                        continue;
                    }

                    double weightMul = 0;// 重量
                    double styleMul = 0;// 款式
                    double sizeMul = 0;// 规格
                    double otherMul = 0;// 其他
                    for (int k = 0; k < skuText.size(); k++) {
                        JSONObject weight = skuText.getJSONObject(k);
                        String visible = weight.getStr("visible");
                        String value = weight.getStr("value");
                        String name = weight.getStr("name");
//                            if (value.equals("约0.19（3mm亮面金珠）")){
//                                System.out.println(value);
//                            }
                        for (String specialSkuStr : SPECIAL_SKU_STR) {
                            value = value.replace(specialSkuStr, "金珠");
                        }
                        if ("SOLID".equals(visible) && (value.contains("g") || value.contains("金珠"))) {
                            if (value.contains("g")) {
                                String[] gArr = value.split("g");
                                value = gArr[0];
                            }
                            Pattern pattern = Pattern.compile("\\d+(\\.\\d+)?");
                            Matcher matcher = pattern.matcher(value);
                            Double g = 0D;
                            while (matcher.find()) {
                                g = Double.valueOf((matcher.group()));
                            }
                            if ("重量".equals(name)) {
                                weightMul = NumberUtil.mul(quantity, g);
                            } else if ("款式".equals(name)) {
                                styleMul = NumberUtil.mul(quantity, g);
                            } else if ("规格".equals(name)) {
                                weightMul = NumberUtil.mul(quantity, g);
                            } else {
                                sizeMul = NumberUtil.mul(quantity, g);
                            }
                        }
                    }
                    double lastMul = weightMul > 0 ? weightMul : styleMul > 0 ? styleMul : sizeMul > 0 ? sizeMul : otherMul;
                    totalG = NumberUtil.add(totalG, lastMul);
                    double subRealTotal = NumberUtil.mul(priceInfo.getDouble("realTotal"), quantity);
                    realTotal = NumberUtil.add(realTotal, subRealTotal);
                }
                String diedLine = operations.getJSONObject(0).getStr("text");
                taobaoOrder.setShopName(seller.getStr("shopName"));
                taobaoOrder.setActualFee(payInfo.getDouble("actualFee"));
                taobaoOrder.setRealTotal(realTotal);
                taobaoOrder.setG(totalG);
                taobaoOrder.setOrderId(mainOrderChild.getStr("id"));
                taobaoOrder.setPostFees(NumberUtils.toDouble(payInfo.getJSONArray("postFees").getJSONObject(0).getStr("value", "0").replace("￥", "")));
                if (SPECIAL_DATE_STR.contains(diedLine)) {
                    taobaoOrder.setDiedLine("未发货");
                } else {
                    taobaoOrder.setDiedLine(diedLine);
                }
                taobaoOrderList.add(taobaoOrder);
            }
        }

        Map<Integer, List<TaobaoOrder>> collect = taobaoOrderList.stream().collect(Collectors.groupingBy(TaobaoOrder::hashCode));
        List<OrderResult> orderResults = new ArrayList<>();
        collect.forEach((integer, taobaoOrders) -> {
            TaobaoOrder taobaoOrder = taobaoOrders.get(0);
            String title = taobaoOrder.getShopName() + " " + taobaoOrder.getDiedLine();
            double gSum = taobaoOrders.stream().map(e -> new BigDecimal(String.valueOf(e.getG()))).reduce(BigDecimal.ZERO, BigDecimal::add).doubleValue();
            double totalActualFeeSum = taobaoOrders.stream().map(e -> new BigDecimal(String.valueOf(e.getActualFee()))).reduce(BigDecimal.ZERO, BigDecimal::add).doubleValue();
            double totalPostFees = taobaoOrders.stream().map(e -> new BigDecimal(String.valueOf(e.getPostFees()))).reduce(BigDecimal.ZERO, BigDecimal::add).doubleValue();
            double realTotal = taobaoOrders.stream().map(e -> new BigDecimal(String.valueOf(e.getRealTotal()))).reduce(BigDecimal.ZERO, BigDecimal::add).doubleValue();
            double avgPrice = 0 == gSum ? 0 : NumberUtil.div(totalActualFeeSum, gSum, 2);// 均价
            double realAvgPrice = 0 == gSum ? 0 : NumberUtil.div(realTotal, gSum, 2);// 均价
            OrderResult orderResult = new OrderResult();
            orderResult.setTitle(title);
            orderResult.setDiedLine(taobaoOrder.getDiedLine());
            orderResult.setAvgPrice(avgPrice);
            orderResult.setGSum(gSum);
            orderResult.setTotalActualFeeSum(totalActualFeeSum);
            orderResult.setRealTotal(realTotal);
            orderResult.setRealAvgPrice(realAvgPrice);
            orderResult.setTotalPostFees(totalPostFees);
            orderResults.add(orderResult);
        });

        orderResults.sort(Comparator.comparing(OrderResult::getDiedLine, String::compareTo));
        System.out.println("克重|实付价格|平均价格|优惠前总价格|优惠前平均价格");
        System.out.println("------------------------------------");
        for (OrderResult orderResult : orderResults) {
            if (NumberUtil.compare(orderResult.getGSum(), 0D) <= 0) {
                continue;
            }
            System.out.println(orderResult.getTitle() + ":");
            StringBuilder sb = new StringBuilder();

            sb.append(StringUtils.rightPad(NumberUtil.toStr(orderResult.getGSum()), 6));
            sb.append(StringUtils.rightPad(NumberUtil.toStr(orderResult.getTotalActualFeeSum()), strLength));
            sb.append(StringUtils.rightPad(NumberUtil.toStr(orderResult.getTotalPostFees()), 4));
            sb.append(StringUtils.rightPad(NumberUtil.toStr(orderResult.getAvgPrice()), strLength));
            sb.append(StringUtils.rightPad(NumberUtil.toStr(orderResult.getRealTotal()), strLength));
            sb.append(StringUtils.rightPad(NumberUtil.toStr(orderResult.getRealAvgPrice()), strLength));
            System.out.println(sb);
        }
        // 导出Excel
        String filePath = PACKAGE_PATH + "订单数据_" + DateUtil.format(new Date(), "yyyy-MM-dd_HH_mm_ss") + ".xlsx"; // 修改为你想要的路径
        FileCleaner.deleteFilesModifiedBeforeToday(PACKAGE_PATH, false);
        exportToExcel(orderResults, filePath);
        ExcelOpener.openExcelFile(filePath);
    }

    // 字段到中文表头的映射
    private static final String[] HEADERS = {
            "时间",
            "商家",
            "标重",
            "买价",
            "运费",
            "平均价格",
            "优惠前总价格",
            "优惠前平均价格"
    };

    public static void exportToExcel(List<OrderResult> dataList, String filePath) {
        // 如果需要生成新的排序列表而不改变原列表
        List<OrderResult> sortedList = dataList.stream().filter(orderResult -> orderResult.getGSum() > 0 && orderResult.getAvgPrice() > 500)
                .sorted(Comparator.comparing(OrderResult::getDiedLine))
                .collect(Collectors.toList());
        System.out.println(JSONUtil.toJsonStr(sortedList));
        // 创建工作簿
        try (Workbook workbook = new XSSFWorkbook()) {
            // 创建工作表
            Sheet sheet = workbook.createSheet("订单数据");
            // 创建表头样式
            CellStyle headerStyle = createHeaderStyle(workbook);

            // 创建表头行
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < HEADERS.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(HEADERS[i]);
                cell.setCellStyle(headerStyle);
            }
            // 创建数据行
            for (int i = 0; i < sortedList.size(); i++) {
                OrderResult order = sortedList.get(i);
                if (NumberUtil.compare(order.getGSum(), 0D) <= 0) {
                    continue;
                }
                Row row = sheet.createRow(i + 1);
                String title = order.getTitle();
                // 用正则分割：旗舰店 或 黄金
                String[] parts = title.split("旗舰店|黄金| |企业店|饰品");
                String titleResult = parts[0].replace("珠宝", "");
                row.createCell(0).setCellValue(order.getDiedLine());
                row.createCell(1).setCellValue(titleResult);
                row.createCell(2).setCellValue(order.getGSum());
                row.createCell(3).setCellValue(order.getTotalActualFeeSum());
                row.createCell(4).setCellValue(order.getTotalPostFees());
                row.createCell(5).setCellValue(order.getAvgPrice());
                row.createCell(6).setCellValue(order.getRealTotal());
                row.createCell(7).setCellValue(order.getRealAvgPrice());
            }

            // 设置表头自适应宽度
            adjustHeaderColumnWidth(sheet);

            // 写入文件
            try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
                workbook.write(outputStream);
                System.out.println("Excel文件已成功导出到: " + filePath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        font.setFontHeightInPoints((short) 12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        return style;
    }

    private static void adjustHeaderColumnWidth(Sheet sheet) {
        // 设置表头自适应宽度（考虑中文字符）
        for (int i = 0; i < HEADERS.length; i++) {
            // 先自动调整
            sheet.autoSizeColumn(i);

            // 因为autoSizeColumn对中文支持不够好，可以手动增加宽度
            int currentWidth = sheet.getColumnWidth(i);
            int newWidth = (int) (currentWidth * 1.3); // 增加20%宽度
            sheet.setColumnWidth(i, Math.min(newWidth, 255 * 256)); // 最大255个字符
        }
    }

    public static String loadStr(String fileName) {
        try (InputStream inputStream = GoldCalc.class.getClassLoader().getResourceAsStream(fileName)) {
            if (inputStream == null) {
                System.err.println("文件未找到: " + fileName);
                return "";
            }

            String content = IoUtil.read(inputStream, StandardCharsets.UTF_8);

            return content;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 从TXT文件中解析多个JSON对象
     *
     * @param content 文件路径
     * @return 解析后的JSON对象列表
     */
    public static List<JSONObject> parseMultipleJsonsFromFile(String content) {
        List<JSONObject> jsonObjects = new ArrayList<>();
        // 分割JSON对象（假设JSON对象之间有空行或换行分隔）
        String[] jsonParts = content.split("(?<=})\\s*(?=\\{)");

        for (String jsonStr : jsonParts) {
            // 去除前后空白字符
            jsonStr = jsonStr.trim();
            if (jsonStr.isEmpty()) {
                continue;
            }

            try {
                // 解析JSON对象
                JSONObject jsonObj = JSONUtil.parseObj(jsonStr);
                jsonObjects.add(jsonObj);
            } catch (Exception e) {
                System.err.println("JSON解析失败: " + e.getMessage());
                System.err.println("问题内容: " + jsonStr);
            }
        }

        return jsonObjects;
    }
}
